import argparse
import subprocess
import re

def get_java_pid_on_port(port):
    """
    获取在指定端口上运行的 Java 进程的 PID（兼容 netstat 和 ss）。
    """
    try:
        # 尝试 ss（推荐），如果失败则尝试 netstat
        cmd = f"ss -tulnp | grep :{port} | grep java"
        result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        if result.returncode != 0:
            cmd = f"netstat -tulnp | grep :{port} | grep java"
            result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        if result.returncode == 0:
            # 使用正则提取 PID
            for line in result.stdout.decode('utf-8').splitlines():
                match = re.search(r'(\d+)/java', line)
                if match:
                    pid = int(match.group(1))
                    print(f"[INFO] Java process is running on port {port} (PID: {pid}).")
                    return pid
        
        # 如果 ss/netstat 失败，尝试 lsof
        cmd = f"lsof -i :{port} | grep java"
        result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        if result.returncode == 0:
            for line in result.stdout.decode('utf-8').splitlines():
                parts = line.split()
                if len(parts) >= 2 and parts[1].isdigit():
                    pid = int(parts[1])
                    print(f"[INFO] Java process is running on port {port} (PID: {pid}).")
                    return pid
        
        print(f"[WARNING] No Java process found on port {port}.")
        return None
    except Exception as e:
        print(f"[ERROR] Failed to check port {port}: {e}")
        return None

def main():
    parser = argparse.ArgumentParser(description="Check if a Java process is running on a specified port and get its PID.")
    parser.add_argument("port", type=int, help="The port number to check (e.g., 8080)")
    
    args = parser.parse_args()
    port = args.port
    
    pid = get_java_pid_on_port(port)
    if pid is not None:
        print(f"Java process PID on port {port}: {pid}")
    else:
        print(f"No Java process found on port {port}.")
# python3 check-port.py 28081
if __name__ == "__main__":
    main()